// 程序三：耗时任务时间采样演示
console.log('=== 耗时任务时间采样演示 ===');

// 模拟耗时任务：计算斐波那契数列
function fibonacci(n) {
    if (n <= 1) return n;
    return fibonacci(n - 1) + fibonacci(n - 2);
}

// 模拟另一个耗时任务：数组排序
function generateRandomArray(size) {
    const arr = [];
    for (let i = 0; i < size; i++) {
        arr.push(Math.random());
    }
    return arr;
}

// 时间采样函数
function timeSampling(taskName, taskFunction) {
    console.log(`\n开始执行任务: ${taskName}`);
    
    // 记录开始时间
    const startTime = process.hrtime.bigint();
    const startTimeMs = Date.now();
    
    // 执行任务
    const result = taskFunction();
    
    // 记录结束时间
    const endTime = process.hrtime.bigint();
    const endTimeMs = Date.now();
    
    // 计算耗时
    const durationNs = endTime - startTime;
    const durationMs = endTimeMs - startTimeMs;
    
    console.log(`任务完成: ${taskName}`);
    console.log(`结果: ${result}`);
    console.log(`耗时 (高精度): ${durationNs} 纳秒`);
    console.log(`耗时 (毫秒): ${durationMs} 毫秒`);
    console.log(`耗时 (秒): ${durationMs / 1000} 秒`);
    
    return {
        taskName,
        durationNs,
        durationMs,
        result
    };
}

// 执行多次采样
const samples = [];

console.log('第一次运行:');
samples.push(timeSampling('斐波那契数列(35)', () => fibonacci(35)));
samples.push(timeSampling('数组排序(10000)', () => {
    const arr = generateRandomArray(10000);
    return arr.sort((a, b) => a - b).length;
}));

console.log('\n第二次运行:');
samples.push(timeSampling('斐波那契数列(35)', () => fibonacci(35)));
samples.push(timeSampling('数组排序(10000)', () => {
    const arr = generateRandomArray(10000);
    return arr.sort((a, b) => a - b).length;
}));

console.log('\n第三次运行:');
samples.push(timeSampling('斐波那契数列(35)', () => fibonacci(35)));
samples.push(timeSampling('数组排序(10000)', () => {
    const arr = generateRandomArray(10000);
    return arr.sort((a, b) => a - b).length;
}));

// 分析结果
console.log('\n=== 时间采样分析 ===');
const fibonacciSamples = samples.filter(s => s.taskName.includes('斐波那契'));
const sortSamples = samples.filter(s => s.taskName.includes('数组排序'));

console.log('\n斐波那契数列任务:');
fibonacciSamples.forEach((sample, index) => {
    console.log(`第${index + 1}次: ${sample.durationMs}ms`);
});

console.log('\n数组排序任务:');
sortSamples.forEach((sample, index) => {
    console.log(`第${index + 1}次: ${sample.durationMs}ms`);
});

// 计算平均值
const avgFibonacci = fibonacciSamples.reduce((sum, s) => sum + s.durationMs, 0) / fibonacciSamples.length;
const avgSort = sortSamples.reduce((sum, s) => sum + s.durationMs, 0) / sortSamples.length;

console.log(`\n斐波那契数列平均耗时: ${avgFibonacci.toFixed(2)}ms`);
console.log(`数组排序平均耗时: ${avgSort.toFixed(2)}ms`);

console.log('\n注意: 由于系统负载、垃圾回收等因素，每次运行的时间可能会有差异。');
